package com.appspot.mypartymanager.mbean.primefaces;

import java.util.List;

import javax.faces.bean.ManagedBean;

import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.submenu.Submenu;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;

import com.appspot.mypartymanager.entity.Party;
import com.appspot.mypartymanager.service.PartyService;
import com.appspot.mypartymanager.service.impl.PartyServiceImpl;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@ManagedBean(name = "menuBean")
public class MenuBean {

	private MenuModel model;

	private User user;

	public MenuBean() {

		model = new DefaultMenuModel();

		// check user info
		UserService userService = UserServiceFactory.getUserService();
		user = userService.getCurrentUser();

		PartyService partyService = new PartyServiceImpl();
		List<Party> userPartys = null;
		
		Submenu submenu = new Submenu();
		submenu.setLabel("My Partys");
		
		//get user partys		
		if (user != null) {
			
			userPartys = partyService.getPartysByUser(user
					.getEmail());
			
			if (userPartys.size() > 0) {

				for (Party p : userPartys) {

					MenuItem item = new MenuItem();
					item.setValue(p.getName());
					// item.setUrl();
					submenu.getChildren().add(item);

				}
				model.addSubmenu(submenu);
			}
		}

		// add new party link
		MenuItem item = new MenuItem();
		if (user != null) {
			if (userPartys.size() > 0) {
				item.setValue("New Party");
				item.setUrl("/pages/party/partyForm.jsf?action=new");
				
			} else {
				item.setValue("Create your first party!");
			}
		} else {
			item.setValue("Create your first party!");
		}
		submenu.getChildren().add(item);

	}

	public MenuModel getModel() {
		return model;
	}

	public String partyPage() {
		return "myParties";
	}

}